import { Ref } from "vue";
import { useSnowflake } from "$/util";
import { useGlobalSettingStore, useUrlStore } from "@/store";
import MessageUtil from "@/utils/model/MessageUtil";
import { TableViewColumnConfig } from "@/domain/TableViewColumnConfig";
import { conditionBuild, orderBuild } from "@/utils/convert/data-browser-condition";
import {
  clientDocDeleteBatchApi,
  clientDocInsertApi,
  clientDocUpdateApi,
  clientSearchDataApi
} from "@/api";

export type { Ref }; // ✅ 关键：让 Ref 成为公共类型

export interface UseDataBrowserInstance {
  id: string;

  index: Ref<string>;

  selectedKeys: Ref<Array<string>>;

  pageNum: Ref<number>;
  pageSize: Ref<number>;
  total: Ref<number>;

  must: Ref<string>;
  should: Ref<string>;
  mustNot: Ref<string>;
  order: Ref<string>;
  columns: Ref<Array<TableViewColumnConfig>>;
  records: Ref<Array<Record<string, any>>>;

  loading: Ref<boolean>;
  run: () => void;
  changeIndex: (res: string) => void;

  add: (data: string) => void;
  update: (id: string, data: string) => void;
  remove: (id: string) => void;
  /**
   * 批量删除
   */
  removeBatch: () => void;
  clear: () => void;

  /**
   * 构建查询条件，JSON字符串
   */
  buildSearchQuery: () => string;
}

export const useDataBrowserInstance = (): UseDataBrowserInstance => {
  // 唯一ID
  const id = useSnowflake().nextId();
  // 当前查询的索引
  const index = ref("");
  const selectedKeys = ref<Array<string>>([]);

  const pageNum = ref(1);
  const pageSize = ref(useGlobalSettingStore().pageSize);
  const total = ref(0);

  // 查询条件
  const must = ref("");
  const should = ref("");
  const mustNot = ref("");
  const order = ref("");

  const loading = ref(false);

  // 显示的列
  const columns = ref<Array<TableViewColumnConfig>>([]);
  // 数据
  const records = ref<Array<Record<string, any>>>([]);

  const run = () => {
    const { id } = useUrlStore();
    if (!id) return MessageUtil.warning("请选择索引");
    if (loading.value) return MessageUtil.warning("正在查询中，请稍后");
    loading.value = true;
    const [res1, res2] = index.value.split(":");
    (() => {
      return clientSearchDataApi(id, {
        index: res1,
        type: res2,
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        must: conditionBuild(must.value),
        should: conditionBuild(should.value),
        mustNot: conditionBuild(mustNot.value),
        order: orderBuild(order.value)
      });
    })()
      .then((r) => {
        columns.value = r.columns;
        records.value = r.records;
        total.value = r.total;
      })
      .catch(() => {
        clear();
      })
      .finally(() => {
        loading.value = false;
      });
  };

  const changeIndex = (res: string) => {
    clear();
    index.value = res;
    run();
  };

  const add = (data: string) => {
    const { id } = useUrlStore();
    if (!id) return MessageUtil.warning("请选择索引");
    if (loading.value) return MessageUtil.warning("正在添加中，请稍后");
    loading.value = true;
    (() => {
      const [res1, res2] = index.value.split(":");
      return clientDocInsertApi(id, res1, data, res2);
    })()
      .then(() => {
        MessageUtil.success("添加成功");
      })
      .catch((e) => {
        MessageUtil.error("添加失败", e);
      })
      .finally(() => {
        loading.value = false;
      });
  };

  const update = (docId: string, data: string) => {
    const { id } = useUrlStore();
    if (!id) return MessageUtil.warning("请选择索引");
    if (loading.value) return MessageUtil.warning("正在修改中，请稍后");
    loading.value = true;
    (() => {
      const [res1, res2] = index.value.split(":");
      return clientDocUpdateApi(id, res1, docId, data, res2);
    })()
      .then(() => {
        MessageUtil.success("修改成功");
      })
      .catch((e) => {
        MessageUtil.error("修改失败", e);
      })
      .finally(() => {});
  };

  const remove = (docId: string) => {
    const { id } = useUrlStore();
    if (!id) return MessageUtil.warning("请选择索引");
    if (loading.value) return MessageUtil.warning("正在删除中，请稍后");
    loading.value = true;
    (() => {
      const [res1, res2] = index.value.split(":");
      return clientDocDeleteBatchApi(id, res1, [docId], res2);
    })()
      .then(() => {
        MessageUtil.success("删除成功");
      })
      .catch((e) => {
        MessageUtil.error("删除失败", e);
      })
      .finally(() => {});
  };

  const removeBatch = () => {
    const { id } = useUrlStore();
    if (!id) return MessageUtil.warning("请选择索引");
    if (loading.value) return MessageUtil.warning("正在删除中，请稍后");
    loading.value = true;
    (() => {
      const [res1, res2] = index.value.split(":");
      return clientDocDeleteBatchApi(id, res1, selectedKeys.value, res2);
    })()
      .then(() => {
        MessageUtil.success("删除成功");
      })
      .catch((e) => {
        MessageUtil.error("删除失败", e);
      })
      .finally(() => {});
  };

  const clear = () => {
    // 此处只是
    columns.value = [];
    records.value = [];
    total.value = 0;
  };

  const buildSearchQuery = (): string => {
    // todo；构建结果集
    return "";
  };

  return {
    id,
    index,
    selectedKeys,
    pageNum,
    pageSize,
    total,
    must,
    should,
    mustNot,
    order,
    columns,
    records,
    loading,
    run,
    changeIndex,
    add,
    update,
    remove,
    removeBatch,
    clear,
    buildSearchQuery
  };
};
